//
//  UIImage+Extension.swift
//  KKWeiBo
//
//  Created by 柯平常 on 16/5/28.
//  Copyright © 2016年 柯平常. All rights reserved.
//

import UIKit

extension UIImage {
    
    //截取当前屏幕
    class func snapShotCurrentWindow() -> UIImage{
        
        let window = UIApplication.shared.keyWindow!
        //开启图形上下文
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, 0)
        
        //将window中显示的内容画到图片上下文中
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        
        //获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    //根据颜色返回图片
    class func imageWithColor(color:UIColor,width:CGFloat,height:CGFloat) -> UIImage{
        UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0)
        color.set()
        UIRectFill(CGRect(x: 0, y: 0, width: width, height: height))
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    
    //  根据指定的宽度等比压缩图片
    func scaleImage(scaleWidth: CGFloat) -> UIImage {
        // 100, 100  -->  200, 200
        //  压缩后的宽度
        let scaleHeight = scaleWidth / self.size.width * self.size.height
        
        let size = CGSize(width: scaleWidth, height: scaleHeight)
        
        //  开启图片上下文
        UIGraphicsBeginImageContext(size)
        //  图片绘制到指定的区域内
        self.draw(in: CGRect(origin: CGPoint.zero, size: size))
        //  获取压缩后的图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        
        
        UIGraphicsEndImageContext()
        
        return scaleImage!
        
        
    }
    
}
